package com.linkgie.galaxyframework.binaryserialize.impl;

import com.linkgie.galaxyframework.binaryserialize.BinaryCodec;
import com.linkgie.galaxyframework.binaryserialize.DataOptions;

import utils.io.BytesOutputBuffer;
import utils.io.BytesSlice;

public class BinaryObjectConverter extends AbstractDynamicValueConverter {
	
	private ObjectRef<BinaryCodec> contractEncoderRef;
	
	
	public BinaryObjectConverter(Class<?> contractType, ObjectRef<BinaryCodec> contractEncoderRef) {
		super(contractType);
		this.contractEncoderRef =contractEncoderRef;
	}

	@Override
	public int encodeDynamicValue(Object value, BytesOutputBuffer buffer, DataOptions options) {
		BytesOutputBuffer contractBuffer = new BytesOutputBuffer();
		int size = contractEncoderRef.get().encode(value, contractBuffer);
		
		size += writeSize(size, buffer);
		
		buffer.write(contractBuffer);
		return size;
	}

	@Override
	public Object decodeValue(BytesSlice dataSlice, DataOptions options) {
		return contractEncoderRef.get().decode(dataSlice.getInputStream());
	}
	
}
